from fastapi import Depends
from typing import Annotated, AsyncGenerator
from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession, create_async_engine
import uuid

from app.models.base import MappedBase

db_url = "sqlite+aiosqlite:///db.sqlite3"

async_engine = create_async_engine(url=db_url, echo=True, future=True)
async_db_session = async_sessionmaker(
    async_engine,
    autoflush=False,
    expire_on_commit=False,
)


async def create_tables():
    async with async_engine.begin() as conn:
        await conn.run_sync(MappedBase.metadata.create_all)


async def get_db() -> AsyncGenerator[AsyncSession]:
    session = async_db_session()
    try:
        yield session
    except Exception as se:
        await session.rollback()
        raise se
    finally:
        await session.close()


def uuid4_str() -> str:
    return str(uuid.uuid4())


SessionDep = Annotated[AsyncSession, Depends(get_db)]
